package com.tgy.programmer_code_interview_guide._03_binarytree;

import com.tgy.leetcode.TreeNode;

/**
 * @Author: tgy
 * @Date: 1/30/21 11:34 AM
 */
public class _03_打印二叉树 {

    public static final String SPACE_STRING = "         ";

    public static String printBinaryTree(TreeNode root) {

        if (root == null) {

            return "";
        }

        StringBuilder sb = new StringBuilder();

        traversalBinaryTree(root,0,0,sb);

        return sb.toString();
    }

    /**
     *
     * @param node
     * @param index
     * @param flag 0 跟节点 1 right, 2 left
     * @param sb
     */
    public static void traversalBinaryTree(TreeNode node,int index,int flag,StringBuilder sb) {

        if (node == null) {
            return;
        }

        traversalBinaryTree(node.right,index+1,1,sb);

        for (int i = 0; i < index; i++){

            sb.append(SPACE_STRING);
        }

        if (flag == 0) {
            sb.append('H').append(node.val).append("H");
        }else if (flag == 1) {
            sb.append("↓").append(node.val);
        }else if (flag == 2) {
            sb.append("↑").append(node.val);
        }
        sb.append("\n");

        traversalBinaryTree(node.left,index+1,2,sb);

    }


    public static void main(String[] args) {

        /**
         *
         *          3
         *        /  \
         *       1    5
         *       \   / \
         *       2  4  6
         *      / \  \
         *    -10 -20 8
         */
        TreeNode root = new  TreeNode(3);

        root.left = new TreeNode(1);
        root.right = new TreeNode(5);
//        root.left.left = new TreeNode(0);
        root.left.right = new TreeNode(2);
        root.left.right.left = new TreeNode(-10);
        root.left.right.right = new TreeNode(-20);
//        root.left.right.right.right = new TreeNode(-30);
//        root.left.right.right.right.left = new TreeNode(-40);

        root.right.left = new TreeNode(4);
        root.right.right = new TreeNode(6);
        root.right.left.right = new TreeNode(8);

        System.out.println(printBinaryTree(root));
    }
}
